<template>
  <div class="exportDialog">
    <el-dialog
      :title="detailObj.title"
      :visible.sync="detailObj.state"
      :show-close="false"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      center
    >
      <div class="block-container">
        <el-form
          ref="form"
          :model="nodeFrom"
          :disabled="editType === '3'"
          label-width="110px"
          style="display: flex;flex-wrap: wrap;align-items: center;"
        >
          <el-form-item label="节点名称">
            <el-input
              v-model="nodeFrom.name"
              v-max-length-tip="30"
              v-no-space
              :disabled="editType === '3'"
            ></el-input>
          </el-form-item>
          <div v-for="(item, index) in moreNodeList" :key="index">
            <el-form-item :label="item.label" v-if="item.label !== 'name'">
              <el-input
                v-model="item.value"
                placeholder="请输入"
                v-no-space
                v-max-length-tip="30"
              ></el-input>
            </el-form-item>
            <!-- <el-form-item v-if="item.inputMethod == '1'" :label="item.label">
              <el-input
                v-model="item.value"
                v-no-space
                v-max-length-tip="30"
              ></el-input>
            </el-form-item>

            <el-form-item
              v-else-if="item.inputMethod == '2'"
              :label="item.label"
            >
              <el-select
                v-model="item.value"
                placeholder="请选择"
                style="width: 100%;"
              >
                <el-option
                  v-for="item in nodeSelectObj[item.label]"
                  :key="item.id"
                  :label="item.name"
                  :value="item.name"
                />
              </el-select>
            </el-form-item> -->
          </div>
        </el-form>
      </div>
      <!--查看节点详情时隐藏-->
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" v-if="editType !== '3'" @click="saveNodeData"
          >确 定</el-button
        >
        <el-button @click="cancelMethod">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import eventBus from '../../utils/eventBus'
import {
  getKnowledgeGraphAll,
  saveKnowledgeGraph,
  getNodeInfoSelect
} from '@/api/knowledgeAddition/index'
import { getDicList } from '@/api/knowledgeTypeAdd/index.js'
import { mapState } from 'vuex'

import { addNode, getNodeDetail } from '@/api/newknowledge/index.js'

export default {
  props: {
    detailObj: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      editor: null,
      command: null,
      undoList: [],
      nodeFrom: {},
      item: {},
      node: {},
      page: {},
      graph: {},
      newDetailObj: {},
      oldDetailObj: {},
      // 编辑类型添加为true，编辑为false
      editType: '1',
      moreNodeList: [],
      nodeSelectObj: {},
      nameObj: null
    }
  },
  watch: {
    detailObj(val) {
      if (val.title === '添加节点') {
        this.editType = '1'
        Object.assign(this.newDetailObj, val)
      } else if (val.title === '编辑节点') {
        this.getNodeDetail(val)
        this.getSelectDataByApi()
        this.editType = '2'
        Object.assign(this.oldDetailObj, val)
      } else {
        this.getSelectDataByApi()
        this.editType = '3'
        Object.assign(this.oldDetailObj, val)
      }
    },
    node(val) {
      if (val && Object.keys(val).length > 0) {
        this.nodeFrom = val
      }
    }
  },
  computed: {
    ...mapState({
      nodeSelect: state => state.know.dictList
    })
  },
  mounted() {
    this.init()
    this.bindEvent()
  },
  methods: {
    // 获取节点详情
    getNodeDetail() {
      getNodeDetail({ nodeId: this.nodeFrom.id }).then(response => {
        this.nodeDetail = response.data.data
        // 把label和value都变成带双引号的字符串
        this.nodeDetail.propertyStr = this.nodeDetail.propertyStr.replace(
          /(?<!")\blabel\b(?=: )/g,
          '"label"'
        )
        this.nodeDetail.propertyStr = this.nodeDetail.propertyStr.replace(
          /(?<!")\bvalue\b(?=: )/g,
          '"value"'
        )
        this.nodeDetail.propertyStr = JSON.parse(this.nodeDetail.propertyStr)
        this.moreNodeList = this.nodeDetail.propertyStr // 把详情查回来的赋值

        // 找到目标对象的索引
        const index = this.moreNodeList.findIndex(item => item.label === 'name')
        if (index !== -1) {
          // 使用 splice 移除目标对象
          const [removedObj] = this.moreNodeList.splice(index, 1)
          this.nameObj = removedObj
        }
      })
    },
    getSelectDataByApi() {
      getNodeInfoSelect().then(res => {
        this.nodeSelectObj = res.data.data
      })
    },
    init() {
      const { editor, command } = this.$parent
      this.editor = editor
      this.command = command
    },
    bindEvent() {
      let self = this
      eventBus.$on('afterAddPage', page => {
        self.page = page
        self.graph = self.page.graph
        eventBus.$on('nodeselectchange', item => {
          if (item.select === true && item.target.getType() === 'node') {
            self.status = 'node-selected'
            self.item = item.target
            // 可以根据node判断选中的是哪个节点
            self.node = item.target.getModel()
          } else {
            self.status = 'canvas-selected'
            self.item = null
            self.node = null
          }
        })
      })
    },
    cancelMethod() {
      // if (this.undoList.length > 0) this.command.undo();
      this.detailObj.state = false
      this.initObjectData()
    },
    async saveNodeData() {
      // 如果是添加节点
      if (this.editType === '1') {
        Object.assign(this.newDetailObj, this.nodeFrom)
        this.command.executeCommand('add', [this.newDetailObj])
        this.nodeFrom = {}
        this.initObjectData()
        this.detailObj.state = false
      }
      // 编辑节点
      else if (this.editType === '2') {
        let flag = false
        Object.assign(this.oldDetailObj, this.nodeFrom)
        // 把label赋值为name，不然label不更新
        this.oldDetailObj.label = this.oldDetailObj.name
        // 再把删除的加回去
        if (this.nameObj !== null) {
          this.nameObj.value = this.nodeFrom.name
          this.moreNodeList.push(this.nameObj)
        }
        if (flag) {
          return this.$message.warning('请填写节点名称')
        }

        this.oldDetailObj.propertyList = this.moreNodeList
        // 调用图谱编辑接口
        const params = {
          nodes: [
            {
              ...this.oldDetailObj
            }
          ]
        }
        await addNode(params).then(response => {
          if (response.data.code !== 200) {
            return this.$message.error(response.data.message)
          }
          this.graph.update(this.item, this.oldDetailObj)
          this.command.executeCommand('update', [this.oldDetailObj])
          this.$bus.$emit('renderCanvas')
          this.detailObj.state = false
          // this.graph.clear()
          // this.graph.render()
          this.initObjectData()
          const tip =
            response.data.message != null ? response.data.message : '操作成功'
          this.$message.success(tip)
        })
      }
    },
    // 初始化对象数据
    initObjectData() {
      this.newDetailObj = {}
      this.oldDetailObj = {}
    },
    /** 获取回显下拉框 */
    getDicList() {
      getDicList({}).then(res => {
        this.nodeSelect = res.data.data
      })
    }
  }
}
</script>
